import { ref, computed } from 'vue';
import { defineStore } from 'pinia';
import { getUserInfo, getAccountList, getMessageCount, getPhonePrefix, postIMOutLogin, getOrderCount } from '@/common/request/api';
import type { CountryAreaItem, AccountItem, UserInfo } from '@/common/request/api';
import IM from '@/common/utils/IM/IM';

export const useUser = defineStore('user', () => {
	// 是否已登录
	const isLogin = ref(false);
	// 用户资料
	const userInfo = ref<UserInfo>(
		uni.getStorageSync('userInfo')||
			{
					code: 0,
					email: '',
					isPayword: false,
					isPhone: false,
					isRepertory: false,
					isRepertoryMsg: '',
					levelIcon: '',
					levelName: '',
					levelNumber: 0,
					msg: '',
					newUser: false,
					nickname: '',
					phone: '',
					photo: '',
					salt: '',
					userId: '',
					userSex: '2',
					countryArea: '',
					imInfo: {
						loginname: '',
						nick: '',
						pd5: '',
						sign: '',
						userThirdId: '',
						userType: 1
					}
			  }
	);
	// 账户列表
	const accountList = ref<AccountItem[]>([]);
	const defaultAccount = computed(() => {
		return accountList.value.find((item) => item.isDefault === 'Y');
	});
	// 是否新人
	const newUser = ref(false);
	// 未读消息数
	const unreadCount = ref(0);
	const orderCount = ref([0, 0, 0, 0]);

	const _getAccountList = async () => {
		const res = await getAccountList();
		accountList.value = res.data;
		return res;
	};
	const getMsgCount = async () => {
		const res = await getMessageCount();
		let count = 0;
		res.data?.forEach((item) => {
			count = count + item.unreadCount;
		});
		unreadCount.value = count;
		return res;
	};

	const _getUserInfo = async () => {
		const res = await getUserInfo();
		isLogin.value = true;
		userInfo.value = res;
		uni.setStorageSync('userInfo', res);
		_getAccountList();
		getOrderCount().then((res) => {
			orderCount.value = [res.pendingOrderCount, res.deliverOrderCount, res.receivingOrderCount, res.evaluateOrderCount, res.refundOrderCount];
		});
		return res;
	};

	//当前区号
	const countryArea = ref<CountryAreaItem>({
		id: -1,
		countryName: '',
		countryCode: '',
		countryArea: ''
	});
	const countryAreaList = ref<CountryAreaItem[]>([]);
	const setCountryArea = (data: CountryAreaItem) => {
		countryArea.value = data;
	};

	const getCountryAreaList = async () => {
		const res = await getPhonePrefix();
		countryAreaList.value = res.data;
		if (countryArea.value.id === -1 && res.data?.length) {
			setCountryArea(res.data[0]);
		}
	};

	const outLogin = async () => {
		uni.removeStorageSync('token');
		uni.removeStorageSync('userInfo');
		isLogin.value = false;
		userInfo.value = { photo: '', nickname: '', phone: '', userId: '' } as UserInfo;
		accountList.value = [];
		newUser.value = false;
		unreadCount.value = 0;
		orderCount.value = [0, 0, 0, 0];
		try {
			await postIMOutLogin();
		} catch (e) {
			//TODO handle the exception
		}
		IM.outLogin();
	};

	return {
		isLogin,
		userInfo,
		orderCount,
		accountList,
		defaultAccount,
		newUser,
		unreadCount,
		countryArea,
		countryAreaList,
		setCountryArea,
		getCountryAreaList,
		getUserInfo: _getUserInfo,
		getAccountList: _getAccountList,
		getMsgCount,
		outLogin
	};
});
